// 游戏解包工具前端逻辑

let currentFileId = null;
let currentPath = null;

// 文件上传
async function uploadFile() {
    const fileInput = document.getElementById('gameFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    const progressBar = document.querySelector('#uploadProgress .progress-bar');
    const progressDiv = document.getElementById('uploadProgress');
    progressDiv.style.display = 'block';

    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        
        if (data.error) {
            alert(data.error);
            return;
        }

        currentFileId = data.file_id;
        
        // 更新进度条
        progressBar.style.width = '50%';
        
        // 开始解包
        const extractResponse = await fetch(`/extract/${currentFileId}`);
        const extractData = await extractResponse.json();
        
        if (extractData.success) {
            progressBar.style.width = '100%';
            
            // 启用功能按钮
            document.getElementById('searchInput').disabled = false;
            document.getElementById('searchBtn').disabled = false;
            document.getElementById('runBtn').disabled = false;
            document.getElementById('reportBtn').disabled = false;
            
            // 加载文件树
            loadFileTree();
            
            setTimeout(() => {
                progressDiv.style.display = 'none';
                alert(`解包完成！游戏类型：${data.game_type}`);
            }, 500);
        } else {
            alert('解包失败：' + extractData.error);
        }
    } catch (error) {
        console.error('上传失败:', error);
        alert('上传失败，请重试');
    }
}

// 加载文件树
async function loadFileTree() {
    if (!currentFileId) return;
    
    const fileTree = document.getElementById('fileTree');
    fileTree.innerHTML = '<div class="text-center"><div class="spinner-border"></div></div>';
    
    try {
        const data = await fetch(`/browse/${currentFileId}`).then(r => r.json());
        fileTree.innerHTML = '';
        renderFileTree(data, fileTree, '');
    } catch (error) {
        fileTree.innerHTML = '<div class="text-danger p-3">加载失败</div>';
    }
}

// 渲染文件树
function renderFileTree(data, container, path) {
    if (data.type === 'directory') {
        data.items.forEach(item => {
            const div = document.createElement('div');
            div.className = 'file-item';
            div.style.paddingLeft = (path.split('/').length * 15) + 'px';
            
            const icon = item.type === 'directory' ? 'folder' : 'file';
            div.innerHTML = `<i class="fas fa-${icon}"></i> ${item.name}`;
            
            div.onclick = () => {
                document.querySelectorAll('.file-item').forEach(el => el.classList.remove('active'));
                div.classList.add('active');
                
                if (item.type === 'file') {
                    loadFileContent(item.path);
                } else {
                    loadDirectory(item.path);
                }
            };
            
            container.appendChild(div);
        });
    }
}

// 加载目录
async function loadDirectory(path) {
    if (!currentFileId) return;
    
    try {
        const data = await fetch(`/browse/${currentFileId}/${path}`).then(r => r.json());
        const fileTree = document.getElementById('fileTree');
        renderFileTree(data, fileTree, path);
    } catch (error) {
        console.error('加载目录失败:', error);
    }
}

// 加载文件内容
async function loadFileContent(path) {
    if (!currentFileId) return;
    
    const fileContent = document.getElementById('fileContent');
    fileContent.innerHTML = '<div class="text-center"><div class="spinner-border"></div></div>';
    
    try {
        const data = await fetch(`/browse/${currentFileId}/${path}`).then(r => r.json());
        
        if (data.type === 'file') {
            fileContent.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">${path}</h6>
                    <small class="text-muted">${data.content.length} 字符</small>
                </div>
                <pre class="code-viewer"><code>${escapeHtml(data.content)}</code></pre>
            `;
        }
    } catch (error) {
        fileContent.innerHTML = '<div class="text-danger">加载失败</div>';
    }
}

// 搜索文件
async function searchFiles() {
    const query = document.getElementById('searchInput').value.trim();
    if (!query || !currentFileId) return;
    
    const searchResults = document.getElementById('searchResults');
    const searchResultsList = document.getElementById('searchResultsList');
    
    searchResultsList.innerHTML = '<div class="text-center"><div class="spinner-border"></div></div>';
    searchResults.style.display = 'block';
    
    try {
        const results = await fetch(`/search/${currentFileId}?q=${encodeURIComponent(query)}`).then(r => r.json());
        
        if (results.length === 0) {
            searchResultsList.innerHTML = '<div class="text-muted">未找到匹配内容</div>';
        } else {
            searchResultsList.innerHTML = results.map(result => `
                <div class="border-bottom pb-2 mb-2">
                    <strong>${result.file}</strong>
                    <p class="text-muted small mb-0">${result.preview}</p>
                </div>
            `).join('');
        }
    } catch (error) {
        searchResultsList.innerHTML = '<div class="text-danger">搜索失败</div>';
    }
}

// 运行游戏
async function runGame() {
    if (!currentFileId) return;
    
    try {
        const data = await fetch(`/run/${currentFileId}`).then(r => r.json());
        
        if (data.error) {
            alert(data.error);
            return;
        }
        
        if (data.type === 'html5') {
            const modal = new bootstrap.Modal(document.getElementById('runModal'));
            document.getElementById('gameFrame').src = data.url;
            modal.show();
        }
    } catch (error) {
        alert('运行失败');
    }
}

// 生成报告
async function generateReport() {
    if (!currentFileId) return;
    
    try {
        const report = await fetch(`/report/${currentFileId}`).then(r => r.json());
        
        // 创建下载链接
        const blob = new Blob([JSON.stringify(report, null, 2)], 
                            { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `game_report_${currentFileId}.json`;
        a.click();
        URL.revokeObjectURL(url);
        
    } catch (error) {
        alert('生成报告失败');
    }
}

// HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 监听回车键搜索
document.getElementById('searchInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        searchFiles();
    }
});

// 监听文件选择
document.getElementById('gameFile').addEventListener('change', function(e) {
    const fileName = e.target.files[0]?.name || '';
    if (fileName) {
        console.log('选择文件:', fileName);
    }
});
